<script setup>

import {
  Delete,
  Download,
  Edit,
  Plus,
  RefreshRight,
  Search,
  Setting,
  ArrowRight,
  CircleCheckFilled,
  WarningFilled,
  TrendCharts,
  CircleCloseFilled,
  DeleteFilled,
  UploadFilled
} from "@element-plus/icons-vue";
import {ref, reactive, onMounted} from 'vue'
import {
  getKnowledgeBaseItemList,
  enableKnowledgeBaseItem,
  disableKnowledgeBaseItem,
  deleteKnowledgeBaseItem
} from "@/api/knowledgebaseItem"
import {useRoute} from "vue-router"
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteKnowledgeBase} from "@/api/knowledgebase";

const currentPage = ref(1)
const pageSize = ref(10)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)
const {query, params} = useRoute()
const dialogVisible = ref(false)
const uploadRef = ref()

onMounted(() => {
  list()
})

const list = () => {
  getKnowledgeBaseItemList({kb_id: query.kb_id, page: currentPage.value, rows: pageSize.value}).then(res => {
    pageInfo.value.total = res.total
    pageInfo.value.list = res.data
  })
}

const searchForm = reactive({
  name: ""
})

const handleSizeChange = (val) => {
  pageSize.value = val
  list()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  list()
}

const pageInfo = ref({
  total: 0,
  list: []
})

const handleCommand = (command) => {
  if (selections.value.length == 0) {
    ElMessage.warning('请选择数据')
    return;
  }
  let idList = selections.value.map(el => el.id)
  if (command === 'enable') {
    enableKnowledgeBaseItem({idList}).then(res => {
      ElMessage.success('启用成功')
      list()
    }).catch(ex => {
      ElMessage.error(ex.message)
    })
  } else if (command === 'disabled') {
    disableKnowledgeBaseItem({idList}).then(res => {
      ElMessage.success('禁用成功')
      list()
    }).catch(ex => {
      ElMessage.error(ex.message)
    })
  } else if (command === 'delete') {
    ElMessageBox.confirm(
        '确认删除吗?',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      deleteKnowledgeBaseItem({idList}).then(res => {
        ElMessage.success('删除成功')
        list()
      }).catch(ex => {
        ElMessage.error(ex.message)
      })
    }).catch(() => {

    })

  }

  if (selections.value.length !== 1) {
    ElMessage.warning('请选择一条数据')
    return;
  }

  if (command === 'parse') {

  } else if (command === 'cancel') {

  }
}

const selections = ref([])

const handleSelectionChange = (val) => {
  selections.value = val
}

const uploadFileList = ref([])
const limit = ref(15)
import service from "@/utils/request";

const uploadFile = (param) => {
  // 创建FormData上传
  let form = new FormData();
  form.append('file', param.file)
  form.enctype = "multipart/form-data";
  // 将附加信息添加至FormData
  form.append("kb_id", query.kb_id);
  // form.append("businessId", this.formId);
  // form.append("businessType", this.formTable);
  //上传操作
  uploadAttach(form, param).then(res => {
    /*上传成功处理*/
    param.onSuccess(res);
  }).catch(err => {
    /*报错处理*/
    ElMessage.error(param.file.name + "上传错误");
    param.onSuccess(err);
    for (let i = 0; i < uploadFileList.value.length; i++) {
      if (param.file.name === uploadFileList.value[i].name) {
        uploadFileList.value.splice(i, 1);
        break;
      }
    }
  });
}

const uploadAttach = (data, fileObject) => {
  return service({
    method: 'post',
    headers: {"Content-Type": "multipart/form-data"},
    url: "/knowledgebase_item/upload/" + query.kb_id, //自定义上传url
    data: data,
    onUploadProgress: progressEvent => {
      fileObject.progressFlag = true;
      fileObject.successFlag = true;
      let percent = (progressEvent.loaded / progressEvent.total * 100) | 0
      fileObject.onProgress({percent});//调用uploader的进度回调
    }
  })
}

// 用户点击上传调用
const upload = async () => {
  // 触发上传 调用配置 :http-request="uploadFile"
  // 即触发 uploadFile函数
  await uploadRef.value.submit()
  // 上传完成后执行的操作 ...
  window.setTimeout(() => {
    ElMessage.success('上传成功')
    dialogVisible.value = false
    uploadFileList.value = []
    list()
  }, 500)

}

const uploadFileProcess = (event, file, fileList) => {
  uploadFileList.value = fileList;
  for (let i = 0; i < uploadFileList.value.length; i++) {
    if (file.name === uploadFileList.value[i].name) {
      uploadFileList.value[i].progressFlag = true;
      uploadFileList.value[i].successFlag = false;
      if (event.percent != 100) {
        uploadFileList.value[i].progressPercent = event.percent;
      } else {
        uploadFileList.value[i].progressPercent = 100;
      }
      break;
    }
  }
}

const handleFileSuccess = (res, file, fileList) => {
  uploadFileList.value = fileList;
  let ret = true;
  for (let i = 0; i < uploadFileList.value.length; i++) {
    if (file.name === uploadFileList.value[i].name) {
      uploadFileList.value[i].progressFlag = true;
      if (file.status == 'success' && res.code == 200) {
        uploadFileList.value[i].successFlag = true;
      } else {
        uploadFileList[i].value.successFlag = false;
        uploadFileList.value.splice(i, 1);
      }
      break;
    }
  }
}

const handleFilePreview = (file) => {
  console.log(file);
}

const handleFileRemove = (file, fileList) => {
  console.log(file);
}

const beforeFileUpload = (file) => {
  //校验文件大小
  if (file.size >= 1024 * 1024 * 1000) {
    //单位GB
    ElMessage.error({
      title: '错误',
      message: `${file.name} 文件大小超出1000M，请重新选择！`
    });
    return false;
  }
}
const beforeFileRemove = (file, fileList) => {

}
const handleFileExceed = (files, fileList) => {
  ElMessage.error({
    title: '错误',
    message: `只能选择${limit.value}个文件，请重新选择文件！`
  });
}

const handleRemove = (fileName, fileList, index) => {
  console.log(fileName, fileList, index);
}

const formatFileSize = (file) => {
  let size = file.size;
  if (size / 1024 > 1024) {
    return (size / 1024 / 1024).toFixed(2) + ' MB';
  } else {
    return (size / 1024).toFixed(2) + ' KB';
  }
}

</script>

<template>
  <div>
    <div style="padding: 10px">
      <div style="margin: 40px 0">
        <h1 style="font-size: 24px">数据集</h1>
        <p>😉 解析成功后才能问答哦。</p>
      </div>
      <div style="display: flex; justify-content: space-between">
        <div>
          <el-dropdown @command="handleCommand">
            <el-button>
              批量操作 <span style="padding-left: 4px"></span>
              <el-icon>
                <ArrowRight/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="enable">
                  <el-icon>
                    <CircleCheckFilled/>
                  </el-icon>
                  启用
                </el-dropdown-item>
                <el-dropdown-item command="disabled">
                  <el-icon>
                    <WarningFilled/>
                  </el-icon>
                  禁用
                </el-dropdown-item>
                <el-dropdown-item command="parse">
                  <el-icon>
                    <TrendCharts/>
                  </el-icon>
                  解析
                </el-dropdown-item>
                <el-dropdown-item command="cancel">
                  <el-icon>
                    <CircleCloseFilled/>
                  </el-icon>
                  取消
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  <el-icon>
                    <DeleteFilled/>
                  </el-icon>
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div>
          <el-input
              v-model="searchForm.name"
              style="width: 240px"
              placeholder="搜索"
              :prefix-icon="Search"
          />
          <el-button type="primary" @click="dialogVisible = true">
            新增文件 <span style="padding-left: 4px"></span>
            <el-icon>
              <Plus/>
            </el-icon>
          </el-button>
        </div>
      </div>
      <el-table :data="pageInfo.list" style="width: 100%" size="large" height="800"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="名称">
          <template #default="scope">
            <div style="padding: 10px 0">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="分块数">
          <template #default="scope">
            <div style="padding: 10px 0">{{ scope.row.chunk_size }}</div>
          </template>
        </el-table-column>
        <el-table-column label="上传日期">
          <template #default="scope">
            <div style="padding: 10px 0">{{ scope.row.createdTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="解析方法">
          <template #default="scope">
            <div style="padding: 10px 0">{{ scope.row.parse }}</div>
          </template>
        </el-table-column>
        <el-table-column label="启用">
          <template #default="scope">
            <div style="padding: 10px 0">
              <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"></el-switch>
              <!-- {{ scope.row.status }}-->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="解析状态">
          <template #default="scope">
            <div style="padding: 10px 0; display: flex">
              <el-alert title="未解析" type="info" style="width: 80px" v-if="scope.row.run == 1"
                        :closable="false"></el-alert>
              <el-alert title="失败" type="error" style="width: 80px" v-else-if="scope.row.run == 2" :closable="false"></el-alert>
              <el-alert title="成功" type="success" style="width: 80px" v-else-if="scope.row.run == 3" :closable="false"></el-alert>
              <el-link :icon="RefreshRight" circle></el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div style="padding: 10px 0">
              <el-link :icon="Edit" circle style="margin-left: 10px"></el-link>
              <el-link :icon="Delete" circle style="margin-left: 10px"></el-link>
              <el-link :icon="Setting" circle style="margin-left: 10px"></el-link>
              <el-link :icon="Download" circle style="margin-left: 10px"></el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 10px">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[100, 200, 300, 400]"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
      <el-dialog v-model="dialogVisible" title="文件上传" width="30%">
        <el-upload
            ref="uploadRef"
            multiple
            action=""
            :file-list="uploadFileList"
            :auto-upload="false"
            :http-request="uploadFile"
            :on-progress="uploadFileProcess"
            :on-success="handleFileSuccess"
            :on-preview="handleFilePreview"
            :on-remove="handleFileRemove"
            :before-upload="beforeFileUpload"
            :before-remove="beforeFileRemove"
            :limit="limit"
            drag
            :on-exceed="handleFileExceed">
          <el-icon class="el-icon--upload">
            <UploadFilled/>
          </el-icon>
          <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              files with a size less than 500kb
            </div>
          </template>
          <template #file="{file, index}">
            <div class="upload-file-list">
              <div style="display: flex; justify-content: space-between; ">
                <div class="file-name" style="width: 46%">{{ file.name }}</div>
                <div class="file-size" style="width: 20%">{{ formatFileSize(file) }}</div>
                <div style="width: 30%">
                  {{ file.progressPercent }}%
                </div>
              </div>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="upload">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.upload-file-list .upload-file-item {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-file-list .file-name,
.upload-file-list .file-size {
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

</style>